package com.wuseguang.springcloud.service.impl;

import com.google.common.primitives.Ints;
import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.dao.jdbc.StudentFacesJdbc;
import com.wuseguang.springcloud.dao.repository.StudentFacesRepository;
import com.wuseguang.springcloud.entity.StudentFaces;
import com.wuseguang.springcloud.service.StudentFacesService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.PaginationUtil;
import com.wuseguang.springcloud.util.PagingTool;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生人脸表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-02-26
 */
@Service
public class StudentFacesServiceImpl  implements StudentFacesService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StudentFacesRepository studentFacesRepository;
    @Autowired
    private StudentFacesJdbc studentFacesJdbc;
    @Autowired
    private ClassCardService classCardServiceImpl;
    @Autowired
    private ClassCardFieldService classCardFieldServiceImpl;



    @Override
    public Result findClassStudentFaces(Integer classid) {
        logger.info("查询学校的人脸信息");
        //按班级查询学生联信息
        String sql = "select s.id,s.student_name,s.class_id,(CASE WHEN  sf.id IS NULL THEN 0  ELSE sf.state  END) state,s.head_portrait,sf.url from " +
                "student_faces sf right JOIN student s on(s.id=sf.student_id  and sf.state !=4)  where s.class_id = ? ";
        //学生人脸信息
        List<Map<String,Object>> list = studentFacesJdbc.queryListMap(sql,classid);

        return new Result(list);
    }

    @Override
    public Result addSutdentFaces(StudentFaces studentFaces) {

          synchronized (this){
              //查询学生人脸信息
              StudentFaces studentFacesTwo =studentFacesRepository.findByStudentId(studentFaces.getStudentId());

              if(studentFacesTwo!=null){
                  return new Result(CodeUtil.FACE_HAS_BEEN_UPLOADED);
              }
              //查询注册失败的信息
              StudentFaces studentFacesThree = studentFacesRepository.findByError(studentFaces.getStudentId());

              logger.info("添加学生人脸信息");

              if(!StringUtils.isEmpty(studentFacesThree)){
                  studentFaces.setId(studentFacesThree.getId());
              }
              //默认为1
              studentFaces.setState(1);
              //未推送
              studentFaces.setPushState(1);
              studentFacesRepository.save(studentFaces);

              if(studentFacesTwo!=null){
                  //把无用的人脸删除
                  studentFacesRepository.deleteById(studentFacesTwo.getId());
              }


              return new Result();
          }
    }

    @Override
    public Result delateStudentFaces(Integer studentId,Integer classId,String schoolId) {
        logger.info("删除学生人脸信息");

        //判断学生是否为0
       if(studentId != 0){
           //查询学生人脸信息
           StudentFaces studentFaces =studentFacesRepository.findByStudentId(studentId);
           //判断人脸时候为空
           if(studentFaces!= null){
               studentFaces.setPushState(1);
               //已经删除未推送
               studentFaces.setState(5);
               studentFacesRepository.save(studentFaces);
           }
           //修改其他部门班级下的所有人脸
           String sql = "UPDATE `student_other_faces` SET `state` = '4' WHERE `student_faces_id` = ?";
           studentFacesJdbc.updateByParameter(sql,studentFaces.getId());

       }


        //查询这个学校其他下面的班级
         String sql = "select CONCAT(c.id) classid from classes c left join grade g on(g.id=c.grade_id)" +
                " where g.school_id=? and g.other = 1";
        //查询这个学校其他下面的班级id
        List<Integer> classList = studentFacesJdbc.queryListInteger(sql,new Object[]{schoolId});

        //班级
        classCardFieldServiceImpl.classesAndCards(classId ,"delfaceflag","1");
        classCardServiceImpl.classesAndCards(classId);

        //其他部门下的班级
        classCardFieldServiceImpl.classesAndCards(classList ,"delfaceflag","1");
        classCardServiceImpl.classesAndCards(classList);


        return new Result();
    }

    @Override
    public Result stuentFacesRegister(int[] classId) {
        List<Integer> list = Ints.asList(classId);
        classCardFieldServiceImpl.classesAndCards(list ,"faceflag","1");
        classCardServiceImpl.classesAndCards(list);
        return new Result();
    }

    @Override
    public Result findSchoolFaces(String schoolId, Integer classId, Integer indexNo, Integer rows, Integer type) {

        logger.info("查询全校的人脸信息");
        String  sql = "SELECT s.id,s.student_name,s.class_id,c.`name`,( " +
                "CASE WHEN sf.id IS NULL THEN 0 WHEN sof.id IS NULL THEN 0 ELSE sof.state END ) " +
                "school_state,s.head_portrait,sf.url ,( CASE WHEN sf.id IS NULL THEN 0 ELSE sf.state END ) state " +
                " FROM student_faces sf RIGHT JOIN student s ON ( s.id = sf.student_id and sf.state =2  ) " +
                "LEFT JOIN classes c on(c.id=s.class_id) LEFT JOIN student_other_faces sof ON " +
                "( sof.student_faces_id = sf.id and sof.class_id =? and (sof.state =0 or sof.state =1  or sof.state =4) )  WHERE s.school_id = ? ";

        //判断查询成功或者失败
        if(type==0){
            logger.info("");
            logger.info("注册成功");
            sql ="select * from ("+sql+") f where school_state in (1,4)";
        }else{
            logger.info("注册失败");
            sql ="select * from ("+sql+") f where school_state in (0,2,3)";
        }

        //学生人脸信息
        List<Map<String,Object>> list = studentFacesJdbc.queryListMap(sql,classId,schoolId);

        sql  = "select   (SELECT COUNT(1) `count` FROM student_faces sf RIGHT JOIN student s ON ( s.id = sf.student_id AND sf.state = 2 ) WHERE  s.school_id = ?) =(SELECT COUNT(1) `count` FROM  " +
                "student_faces sf RIGHT JOIN student s ON ( s.id = sf.student_id AND sf.state = 2 ) WHERE s.school_id = ? and sf.state =2) `string`";
        String status = studentFacesJdbc.queryString(sql,schoolId,schoolId);



        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);

        Map<String ,Object> map = new HashMap<>();
        map.put("list",new PaginationUtil<>(list.size(),rows, tool.getList(), indexNo));
        map.put("status",status);

        return new Result(map);
    }

    @Override
    public Result synchronizeFaces(String schoolId,Integer classId) {

        //把符合条件的数据同步到另外一张表
        String  sql = "INSERT INTO student_other_faces(student_faces_id,class_id,state,school_id)" +
                "select sf.id ,? ,0, sf.school_id  from ( SELECT sf.*,sof.id sofid FROM student_faces sf " +
                " left JOIN  student_other_faces sof on(sof.student_faces_id=sf.id and  sof.state  in(0,1,4) " +
                "and sof.class_id =? ) where sf.state = 2 and sf.school_id =?  ) sf where sf.sofid is  null";
        studentFacesJdbc.updateByParameter(sql,classId,classId,schoolId);

        logger.info("把信息同步到校牌");
         sql = "select b.deviceid string from bancard b LEFT join classroom c on(b.classroomid=c.id) where c.classid=? ";
        //查询设备id
        String deviceid = studentFacesJdbc.queryString(sql,classId);
        classCardFieldServiceImpl.deviceidAndCards(deviceid ,"faceflag","1");
        classCardServiceImpl.deviceidAndCards(deviceid);
        return new Result();
    }
}
